<template>
  <template v-if="disabled">
    {{ selectedOptionTitle }}
  </template>
  <el-select v-model="dictValue" clearable :placeholder="placeholder"
             filterable style="width: 100%" v-else>
    <el-option v-for="opt in dictOptions" :key="opt.value"
               :label="opt.title" :value="opt.value"/>
  </el-select>
</template>
<script setup>
import {computed, toRaw, unref, watchEffect} from 'vue';
import SystemDicts from '@/components/SystemDict/SystemDicts';
import {isEmpty, isNotEmpty} from '@/utils/CommonUtils';

defineOptions({
  name: 'SystemDict'
});

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  modelValue: undefined,
  defaultValue: undefined,
  placeholder: undefined,
  dictCode: undefined
});

const emits = defineEmits(['update:modelValue']);

const dictValue = computed({
  get() {
    return toRaw(props.modelValue);
  },
  set(value) {
    emits('update:modelValue', value);
  },
});
const dictOptions = computed(() => {
  let options = SystemDicts[toRaw(props.dictCode)];
  if (isNotEmpty(options)) return options;
  return [];
});

watchEffect(() => {
  if (isNotEmpty(props.defaultValue)) {
    emits('update:modelValue', props.defaultValue);
  }
})

const selectedOptionTitle = computed(() => {
  if (isEmpty(props.modelValue) && props.modelValue !== false) return undefined;
  return unref(dictOptions)?.find(o => o.value === toRaw(props.modelValue))?.title;
});
</script>
<script>
export default {
  name: 'SystemDict'
}
</script>
